import {Alert, Linking, SafeAreaView, StyleSheet} from 'react-native';
import {Button, Text, TextInput, View} from 'M/UI/Libraries';
import React from 'react';
import {L} from 'lc-simple-js-common';

import {buildSign, getUrlParams} from 'WE/Utils';
import {globalService} from 'M/Services';

export default function () {
  React.useEffect(() => {
    (async () => {
      const subscription = globalService.addLinkingEventListener(url => {
        if (url) {
          const {data} = getUrlParams(url);
          const {
            message,
            res: {paymentId, amount},
          } = JSON.parse(data || '{}');
          Alert.alert(
            '订单信息',
            '支付单号：' + paymentId + ',金额：' + amount + ',状态:' + message,
          );
        }
      });
      return () => subscription.remove();
    })().then(s => console.log(s));
  }, []);

  const [appCode, setAppCode] = React.useState('chang_chang_card');
  const [appId, setAppId] = React.useState('uphrrLZiOI');
  const [appKey, setAppKey] = React.useState(
    'z50btjQwaJdtqIgXlWKwf9GskhYo30Ws',
  );
  const [amount, setAmount] = React.useState('0.01');
  const [orderId, setOrderId] = React.useState(L.randomCode(10));

  const pressMe = async () => {
    const randomCode = L.randomCode(10);
    let data = {
      appId,
      amount,
      orderId,
      showDeepLink: 1,
      randomCode,
      currency: 'USD',
    };
    data.sign = buildSign({data, appKey});
    try {
      const response = await lpRequest.post({
        url: `v3/${appCode}/receive/payment/orders`,
        data,
      });
      const {appDeepLink, appDownloadLink} = (response.data || {}).data;
      if (appDeepLink && !(await Linking.canOpenURL(appDeepLink))) {
        const url = `${appDeepLink}&appCallbackDeepLink=weskinny://we.skinny`;
        console.log('url', url);
        let value = await Linking.openURL(url);
        console.log('value', value);
      } else if (appDownloadLink) {
        await Linking.openURL(appDownloadLink);
      }
    } catch (e) {
      Alert.alert('下单失败', e.message);
    }
  };
  return (
    <SafeAreaView style={[styles.viewContent]}>
      <View style={styles.view}>
        <Text style={styles.text}>应用编码</Text>
        <TextInput
          style={styles.input}
          onChangeText={setAppCode}
          value={appCode}
          placeholder="应用编码(App Code)，龙支付提供"
        />
      </View>
      <View style={styles.view}>
        <Text style={styles.text}>应用Id</Text>
        <TextInput
          style={styles.input}
          onChangeText={setAppId}
          value={appId}
          placeholder="应用Id(App Id)，商户后台中获取"
        />
      </View>
      <View style={styles.view}>
        <Text style={styles.text}>应用Key</Text>
        <TextInput
          style={styles.input}
          onChangeText={setAppKey}
          value={appKey}
          placeholder="应用Key(App Key)，商户后台中获取"
        />
      </View>
      <View style={styles.view}>
        <Text style={styles.text}>订单金额</Text>
        <TextInput
          style={styles.input}
          onChangeText={setAmount}
          value={amount}
          placeholder="0.01"
        />
      </View>
      <View style={styles.view}>
        <Text style={styles.text}>订单号</Text>
        <TextInput
          style={styles.input}
          onChangeText={setOrderId}
          value={orderId}
          placeholder="本地订单号"
        />
      </View>
      <View style={styles.btnView}>
        <Button title="创建单据" onPress={pressMe} />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  viewContent: {
    padding: 10,
    flex: 1,
    marginHorizontal: 16,
  },
  btnView: {
    textAlign: 'center',
    marginVertical: 8,
  },
  view: {
    flexDirection: 'row',
  },
  text: {
    paddingTop: 22,
    width: 60,
  },

  input: {
    height: 40,
    margin: 12,
    width: '70%',
    borderWidth: 1,
    padding: 10,
  },
});
